#!/bin/bash

VENV=.venv

# exit on error
set -e 

# create virtual env
python -m venv $VENV

# activate environment
source $VENV/bin/activate

pip install trame trame-vtk trame-vuetify trame-components trame-server trame-iframe

pip install --upgrade asyncio 
pip install --upgrade nest_asyncio 
pip install --upgrade numba 

# for our GLTF importer
pip install --upgrade wheel
pip install --upgrade pygltflib numpy 

# install packages for building VTK
sudo apt-get install -y cmake g++
sudo apt-get install -y libopengl-dev libgl-dev libegl-dev python3-dev

# install apache2 if necessary...
sudo apt-get install -y apache2 apache2-utils

# download vtk
mkdir -p vtk
wget -c https://vtk.org/files/release/9.2/VTK-9.2.6.tar.gz -P vtk

#build vtk...
tar -zxf vtk/VTK-9.2.6.tar.gz --directory vtk
mkdir -p vtk/build
cmake -B vtk/build -S vtk/VTK-9.2.6 \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=$VENV \
    -DVTK_GROUP_ENABLE_Web=WANT \
    -DVTK_OPENGL_HAS_EGL=ON \
    -DVTK_USE_X=OFF \
    -DVTK_WRAP_PYTHON=ON

# TODO: -j8 works on my PC...
cmake --build   vtk/build -j8
cmake --install vtk/build

# create directories
mkdir -p www 
mkdir -p logs/apache
mkdir -p logs/launcher

# create proxy mapping file
touch proxy-mapping.txt

# create www folder, vue3 not work yet... 这句代码就是编译输出前端的组件库
python -m trame.tools.www --output www --client-type vue2

# create apache site config
sed 's:%ROOT%:'`pwd`':g' ./001-trame.conf | sudo tee /etc/apache2/sites-enabled/001-trame.conf

# enable modules
sudo a2enmod headers
sudo a2enmod vhost_alias
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel
sudo a2enmod rewrite

# add current user to apache group...
# TODO: use a more reasonable method to access...
sudo adduser www-data $(whoami)

# restart apache...
sudo service apache2 restart

deactivate
exit 0